package com.quantstack.llcommonlibrary.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.ReplacementTransformationMethod;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.databinding.BindingAdapter;
import androidx.databinding.InverseBindingAdapter;
import androidx.databinding.InverseBindingListener;
import androidx.databinding.InverseBindingMethod;
import androidx.databinding.InverseBindingMethods;

import com.quantstack.llcommonlibrary.R;
import com.quantstack.llcommonlibrary.utils.LogUtils;

import java.util.regex.Pattern;

/**
 * @author wu_ming_zhi_bei
 * @date 2021/2/23 16:52
 * @Notes 认证输入框
 */
@InverseBindingMethods({
        @InverseBindingMethod(
                type = AuthItem.class,
                attribute = "inputValue",
                event = "onInputValueAttrChanged",
                method = "getInputValue")
})
public class AuthItem extends LinearLayout {
    private Context mContext;
    private TextView tvTitle;
    private TextView tvError;
    private EditText etEdit;
    private int titleColor;

    public AuthItem(Context context) {
        this(context,null);
    }

    public AuthItem(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public AuthItem(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context,attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        mContext = context;
        //加载布局
        LayoutInflater.from(context).inflate(R.layout.layout_auth_item,this);
        tvTitle = findViewById(R.id.tv_title);
        tvError = findViewById(R.id.tv_error);
        etEdit = findViewById(R.id.et_edit);

        TypedArray a = mContext.obtainStyledAttributes(attrs, R.styleable.AuthItem);
        int titleSize = a.getDimensionPixelSize(R.styleable.AuthItem_titleSize,14);
        titleColor = a.getColor(R.styleable.AuthItem_titleColor,getResources().getColor(R.color.c999));
        String title = a.getString(R.styleable.AuthItem_title);

        tvTitle.setTextColor(titleColor);
        tvTitle.setTextSize(TypedValue.COMPLEX_UNIT_SP,titleSize);
        tvTitle.setText(title);

        int errorSize = a.getDimensionPixelSize(R.styleable.AuthItem_errorSize,12);
        int errorColor = a.getColor(R.styleable.AuthItem_errorColor,getResources().getColor(R.color.cf00));
        tvError.setTextColor(errorColor);
        tvError.setTextSize(TypedValue.COMPLEX_UNIT_SP,errorSize);

        int editSize = a.getDimensionPixelSize(R.styleable.AuthItem_editSize,16);
        int editColor = a.getColor(R.styleable.AuthItem_editColor,getResources().getColor(R.color.c333));
        a.recycle();
        etEdit.setTextColor(editColor);
        etEdit.setTextSize(TypedValue.COMPLEX_UNIT_SP,editSize);

        //设置edit获取焦点的时候标题变色
        etEdit.setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus){
                    tvTitle.setTextColor(getResources().getColor(R.color.auth_edit_color));
                    if(onEditListener!=null){
                        onEditListener.onFocusChange(true);
                    }
                }else{
                    tvTitle.setTextColor(titleColor);
                    if(onEditListener!=null){
                        onEditListener.onFocusChange(false);
                    }
                }
            }
        });

        //设置内容改变监听
        etEdit.addTextChangedListener(new SimpleTextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                super.afterTextChanged(s);
                String str = s.toString();
                if(!TextUtils.isEmpty(str)){
                    //隐藏错误提示
                    tvError.setVisibility(GONE);
                    if(etEdit.isEnabled()){
                        tvTitle.setTextColor(getResources().getColor(R.color.auth_edit_color));
                    }else{
                        //如果是禁用模式下那说明是在选择，所以给当前焦点
                        //etEdit.setFocusable(true);
                        //etEdit.setFocusableInTouchMode(true);
                        //etEdit.requestFocus();
                        //tvTitle.setTextColor(getResources().getColor(R.color.theme_color));
                    }

                    if(onEditListener!=null){
                        onEditListener.onTextChange(str);
                    }
                }

            }
        });
    }

    /**
     * 设置错误提示信息
     * @param
     */
    public void setError(String error){
        if(!TextUtils.isEmpty(error)){
            tvError.setVisibility(VISIBLE);
            tvError.setText(error);
        }else{
            tvError.setVisibility(GONE);
            tvTitle.setTextColor(titleColor);
        }
    }


    public void setOnEditListener(OnEditListener onEditListener){
        this.onEditListener = onEditListener;
    }
    private OnEditListener onEditListener;
    public interface OnEditListener{
        void onFocusChange(boolean hasFocus);
        void onTextChange(String s);
    }

    /**
     * 设置值
     * @param text
     */
    public void setText(String text){
        if(!TextUtils.isEmpty(text)){
            etEdit.setText(text);
        }
    }

    /**
     * 数据回显的时候解决标题栏变色的bug
     */
    public void resetTitleColor(){
        tvTitle.setTextColor(titleColor);
    }

    /**
     * 禁用edit输入
     */
    public void setEditEanble(boolean b){
        etEdit.setEnabled(b);
    }

    /**
     * 如果edit不可用 那么父组件就拦截点击的事件弹出选择
     * @param ev
     * @return
     */
    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if(!etEdit.isEnabled()){
                    return true;//父布局拦截事件
                }
        }
        return false;
    }

    /**
     * 设置最大输入长度
     */
    public void setMaxLength(int length){
        if(length>0){
            etEdit.setFilters(new InputFilter[]{new InputFilter.LengthFilter(length)});//20
        }
    }

    /**
     * 设置输入显示 和长度显示
     */
    public void setInputTypeAndMaxLength(final String regex,int mexLength){
        //设置过滤
        if(!TextUtils.isEmpty(regex)){
           etEdit.setFilters(new InputFilter[]{
                   new InputFilter() {
                       @Override
                       public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                           boolean b = Pattern.matches(regex, source.toString());
                           if (!b) {
                               return "";
                           }
                           return null;
                       }
                   },
                   new InputFilter.LengthFilter(mexLength)
           });
        }
    }

    /**
     * 输入内容自动大写
     */
    public void setInputUpperCase(){
        etEdit.setTransformationMethod(new TransInformation());
    }

    /**
     * @author wu_ming_zhi_bei
     * @date 2020/3/19 15:15
     * @Notes
     */
    //原本输入的小写字母
    class TransInformation extends ReplacementTransformationMethod {
        /**
         * 原本输入的小写字母
         */
        @Override
        protected char[] getOriginal() {
            return new char[]{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
        }

        /**
         * 替代为大写字母
         */
        @Override
        protected char[] getReplacement() {
            return new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
        }
    }

    /**
     * 设置获取焦点
     */
    public void setEditfocus(){
        etEdit.setFocusable(true);
        etEdit.setFocusableInTouchMode(true);
        etEdit.requestFocus();
        etEdit.findFocus();
    }

    /**
     * 获取输入值
     * @return
     */
    public String getEditText(){
        return etEdit.getText().toString().trim();
    }

    //InverseBindingAdapter用于关联某个用于接收View变更的方法
    @InverseBindingAdapter(attribute = "inputValue", event="inputValueAttrChanged")
    public static String getInputValue(AuthItem view) {
        return view.getEditText();
    }

    //BindingAdapter用来设置布局中View的自定义属性，当使用该属性时，可以自定义其行为。
    /**
     * 1、作用于方法
     * 2、它定义了xml的属性赋值的java实现
     * 3、方法必须为公共静（public static）方法，可以有一到多个参数。
     */
    @BindingAdapter({"inputValue"})
    public static void setInputValue(AuthItem authItem, String value){
        if(authItem!=null){
            value = value == null ? "" : value;
            if(authItem.getEditText().equals(value)){
                return;
            }
           authItem.setText(value);
        }
    }

    @BindingAdapter(value = {"inputValue","inputValueAttrChanged"}, requireAll = false)
    public static void setOnInputValueAttrChanged(AuthItem view,
                                                final OnEditListener onEditListener,
                                                final InverseBindingListener bindingListener) {

        LogUtils.e("setOnInputValueAttrChanged：变化");
        if (bindingListener == null) {
            LogUtils.e("ssssssssdsd");
            view.setOnEditListener(onEditListener);
        } else {
            view.setOnEditListener(new OnEditListener() {
                @Override
                public void onFocusChange(boolean hasFocus) {
                    if(onEditListener!=null){
                        onEditListener.onFocusChange(hasFocus);
                    }
                }

                @Override
                public void onTextChange(String s) {
                    if(onEditListener!=null){
                        onEditListener.onTextChange(s);
                    }else{
                        // 通知 ViewModel
                        bindingListener.onChange();
                    }
                }
            });
        }
    }

    /**
     * 设置下拉选择的样式
     */
    public void setSelectBorder(){
        etEdit.setBackground(getResources().getDrawable(R.drawable.bg_edittext_focused));
        tvTitle.setTextColor(getResources().getColor(R.color.auth_edit_color));
    }

    /**
     * 设置下拉选择的没有选中样式
     */
    public void setUnSelectBorder(){
        etEdit.setBackground(getResources().getDrawable(R.drawable.bg_edittext_normal));
        tvTitle.setTextColor(titleColor);
    }

    public void setEditDisable(){
        etEdit.setOnFocusChangeListener(null);
        etEdit.setKeyListener(null);
        etEdit.setBackgroundColor(getResources().getColor(R.color.cf5));
    }
}
